package com.cykj.service.serviceImpl;

import com.cykj.Mapper.wordUserMapper;
import com.cykj.pojo.AllMaxContext;
import com.cykj.pojo.Project;
import com.cykj.pojo.User;
import com.cykj.service.WordCreateService1;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

@Service
public class wordCreateServiceimpl implements WordCreateService1 {

    @Autowired
    private wordUserMapper wordCreateMapper;

    @Override
    public void exportWordReport(String filePath, int userId, int orderId) {
        try {
            // 创建 Word 文档对象
            XWPFDocument document = new XWPFDocument();

            // 添加标题
            XWPFParagraph titleParagraph = document.createParagraph();
            XWPFRun titleRun = titleParagraph.createRun();
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);
            titleRun.setFontSize(24);
            titleRun.setText("体检报告");
            titleRun.setColor("0000FF");
            titleRun.setFontFamily("Comic Sans MS"); // 设置俏皮字体
            titleRun.addBreak();

            // 获取用户数据和项目数据
            List<User> allUsers = wordCreateMapper.findAllUsers(userId);
            List<Project> projects = wordCreateMapper.finAllProject(userId);

            // 用户基本信息部分
            XWPFParagraph userInfoParagraph = document.createParagraph();
            userInfoParagraph.setSpacingAfter(30);
            userInfoParagraph.setSpacingBefore(30);
            XWPFRun userInfoRun = userInfoParagraph.createRun();
            userInfoRun.setFontSize(12);
            userInfoRun.setBold(true);
            userInfoRun.setText("用户基本信息：");
            userInfoRun.setFontFamily("Comic Sans MS");
            for (User user : allUsers) {
                XWPFParagraph userDetailParagraph = document.createParagraph();
                userDetailParagraph.setSpacingAfter(15);
                userDetailParagraph.setSpacingBefore(15);
                XWPFRun userDetailRun = userDetailParagraph.createRun();
                userDetailRun.setText("姓名：" + user.getUserName());
                userDetailRun.addBreak();
                userDetailRun.setText("年龄：" + user.getUserAge());
                userDetailRun.addBreak();
                userDetailRun.setText("性别：男");
                userDetailRun.addBreak();
                userDetailRun.setText("身份证号：" + user.getUserIdNumber());
                userDetailRun.addBreak();
                userDetailRun.setText("身高：" + user.getUserHeight());
                userDetailRun.addBreak();
                userDetailRun.setText("体重：" + user.getUserWeight());
                userDetailRun.addBreak();
                AllMaxContext allMaxContext = wordCreateMapper.allMaxContext(orderId);
                userDetailRun.setText("体检总评价：" + allMaxContext.getMaxContext());
                userDetailRun.addBreak();
            }

            // 随机生成关心语言
            String[] careMessages = {
                    "亲爱的朋友，健康是人生最大的财富。请珍惜这份体检报告，关爱自己的身体。",
                    "您的健康是我们的牵挂。这份体检报告是您了解自己身体的重要依据，愿您生活充满活力。",
                    "健康是幸福的基石。认真对待体检报告，开启健康生活新篇章。"
            };
            Random random = new Random();
            int randomIndex = random.nextInt(careMessages.length);
            String careMessage = careMessages[randomIndex];

            // 添加关心语言
            XWPFParagraph careParagraph = document.createParagraph();
            careParagraph.setSpacingAfter(30);
            careParagraph.setSpacingBefore(30);
            XWPFRun careRun = careParagraph.createRun();
            careRun.setFontSize(12);
            careRun.setText(careMessage);
            careRun.setFontFamily("Comic Sans MS");
            careRun.addBreak();

            // 体检项目部分
            XWPFParagraph projectInfoParagraph = document.createParagraph();
            projectInfoParagraph.setSpacingAfter(30);
            projectInfoParagraph.setSpacingBefore(30);
            XWPFRun projectInfoRun = projectInfoParagraph.createRun();
            projectInfoRun.setFontSize(12);
            projectInfoRun.setBold(true);
            projectInfoRun.setText("体检项目信息：");
            projectInfoRun.setFontFamily("Comic Sans MS");
            for (Project project : projects) {
                XWPFParagraph projectDetailParagraph = document.createParagraph();
                projectDetailParagraph.setSpacingAfter(15);
                projectDetailParagraph.setSpacingBefore(15);
                XWPFRun projectDetailRun = projectDetailParagraph.createRun();
                projectDetailRun.setText("项目名称：" + project.getProjectName());
                projectDetailRun.addBreak();
                projectDetailRun.setText("项目单价：" + project.getProjectPrice());
                projectDetailRun.addBreak();
                projectDetailRun.setText("项目内容：" + project.getProjectContext());
                projectDetailRun.addBreak();
            }

            // 宣传部分
            XWPFParagraph promotionParagraph = document.createParagraph();
            promotionParagraph.setSpacingAfter(30);
            promotionParagraph.setSpacingBefore(30);
            XWPFRun promotionRun = promotionParagraph.createRun();
            promotionRun.setFontSize(12);
            promotionRun.setText("我们致力于为您提供最专业、最全面的体检服务。选择我们，就是选择健康。欢迎您下次再来！");
            promotionRun.setFontFamily("Comic Sans MS");
            promotionRun.addBreak();

            // 添加二维码（空白，无内容）
            XWPFParagraph qrParagraph = document.createParagraph();
            qrParagraph.setAlignment(ParagraphAlignment.RIGHT);
            XWPFRun qrRun = qrParagraph.createRun();
            try {
                // 生成空白二维码
                int width = 100;
                int height = 100;
                BufferedImage qrImage = generateBlankQRCode(width, height);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(qrImage, "png", baos);
                byte[] qrBytes = baos.toByteArray();

                // 创建新的图片段落并添加到文档
                XWPFParagraph imageParagraph = document.createParagraph();
                XWPFRun imageRun = imageParagraph.createRun();
                imageRun.addPicture(new ByteArrayInputStream(qrBytes), Document.PICTURE_TYPE_PNG, "qr.png", 100, 100);
            } catch (Exception e) {
                e.printStackTrace();
            }

            FileOutputStream out = new FileOutputStream(filePath);
            document.write(out);
            out.close();
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BufferedImage generateBlankQRCode(int width, int height) {
        BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = qrImage.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.BLACK);
        // 可以绘制一些简单的图案来代表空白二维码，比如画一个小方块
        g2d.fillRect(width / 4, height / 4, width / 2, height / 2);
        g2d.dispose();
        return qrImage;
    }
}
